package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.domain.AppUser;
import com.ruoyi.web.domain.UserQuestion;
import com.ruoyi.web.dto.UserQuestionDTO;
import com.ruoyi.web.enums.CommonDictEnum;
import com.ruoyi.web.mapper.UserQuestionMapper;
import com.ruoyi.web.service.IAppUserService;
import com.ruoyi.web.service.IUserQuestionService;
import com.ruoyi.web.vo.UserQuestionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户提问Controller
 *
 * @author ruoyi
 * @date 2023-01-17
 */
@RestController
@RequestMapping("/question")
public class UserQuestionController extends BaseController {
    @Autowired
    private IUserQuestionService userQuestionService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private UserQuestionMapper questionMapper;

    /**
     * 查询用户提问列表
     */
    @GetMapping("/app/list")
    public TableDataInfo list(UserQuestion userQuestion) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new TadpoleException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
        }
        userQuestion.setLaunchUserId(userId);
        List<UserQuestion> list = userQuestionService.selectUserQuestionList(userQuestion);
        TableDataInfo info = getDataTable(list);

        List<UserQuestionVO> voList = new ArrayList<>();
        for (UserQuestion question : list) {
            UserQuestionVO vo = new UserQuestionVO();
            BeanUtils.copyProperties(question, vo);
            vo.setIsAnswer(CommonDictEnum.YesOrNo.findName(vo.getIsAnswer()));
            voList.add(vo);
        }
        return getDataTable(info, voList);
    }

    @GetMapping("/page/list")
    public TableDataInfo page(UserQuestion userQuestion) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<UserQuestion> questions;
        if (loginUser.getUser().getRoles().get(0).getRoleId() == 3) {
            // 获取所有子集
            List<AppUser> userList = new ArrayList<>();
            appUserService.getAllChild(userList, loginUser.getUserId());
            List<Long> list = userList.stream().map(AppUser::getId).collect(Collectors.toList());
            startPage();
            questions = questionMapper.selectChildUserQuestionList(new UserQuestionDTO() {{
                setUserList(list);
            }});
        } else {
            startPage();
            questions = userQuestionService.selectUserQuestionList(userQuestion);
        }
        TableDataInfo info = getDataTable(questions);

        List<UserQuestionVO> voList = new ArrayList<>();
        for (UserQuestion question : questions) {
            UserQuestionVO vo = new UserQuestionVO();
            BeanUtils.copyProperties(question, vo);
            vo.setIsAnswer(CommonDictEnum.YesOrNo.findName(vo.getIsAnswer()));
            voList.add(vo);
        }
        return getDataTable(info, voList);
    }

    /**
     * 提问
     *
     * @param question 问题
     * @return r
     */
    @PostMapping("/save")
    public R<String> createQuestion(@RequestBody UserQuestion question) {
        if (question == null || question.getQuestion() == null || question.getQuestion().isEmpty()) {
            throw new TadpoleException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(), "Question cannot be empty");
        }
        return userQuestionService.createQuestion(question.getQuestion());
    }

    /**
     * 回复
     *
     * @param question 回复
     * @return r
     */
    @PutMapping("/update")
    public R<String> answerQuestion(@RequestBody UserQuestion question) {
        return userQuestionService.answerQuestion(question);
    }

    /**
     * 导出用户提问列表
     */
    @PreAuthorize("@ss.hasPermi('web:question:export')")
    @Log(title = "用户提问", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserQuestion userQuestion) {
        List<UserQuestion> list = userQuestionService.selectUserQuestionList(userQuestion);
        ExcelUtil<UserQuestion> util = new ExcelUtil<UserQuestion>(UserQuestion.class);
        util.exportExcel(response, list, "用户提问数据");
    }

    /**
     * 获取用户提问详细信息
     */
    @PreAuthorize("@ss.hasPermi('web:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        UserQuestion question = userQuestionService.selectUserQuestionById(id);
        UserQuestionVO vo = new UserQuestionVO();
        BeanUtils.copyProperties(question, vo);
        vo.setIsAnswer(CommonDictEnum.YesOrNo.findName(vo.getIsAnswer()));
        return success(vo);
    }

    /**
     * 删除用户提问
     */
    @PreAuthorize("@ss.hasPermi('web:question:remove')")
    @Log(title = "用户提问", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userQuestionService.deleteUserQuestionByIds(ids));
    }
}
